import { CSSProperties, FC, HTMLAttributes, useRef } from 'react';

import { useDrag, useDrop } from 'react-dnd';

import './index.less';

interface DragAbleRowProps extends HTMLAttributes<HTMLTableRowElement> {
  index: number;
  moveRow: (dropIndex: number, dragIndex: number) => void;
  className: string;
  style: CSSProperties;
  dragType: string;
}

const DragAbleRow: FC<DragAbleRowProps> = ({
  dragType,
  index,
  moveRow,
  className,
  style,
  ...restProps
}) => {
  const trRef = useRef<HTMLTableRowElement>(null);
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: dragType,
    collect: (monitor: any) => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? ' drop-over-downward' : ' drop-over-upward',
      };
    },
    drop: (item: any) => {
      moveRow(item.index, index);
    },
  });

  const [, drag] = useDrag({
    type: dragType,
    item: { index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),
  });

  drop(drag(trRef));

  return (
    <tr
      ref={trRef}
      className={`${className} ${isOver ? dropClassName : ''}`}
      style={{ cursor: 'move', ...style }}
      {...restProps}
    />
  );
};

DragAbleRow.defaultProps = {
  dragType: 'DragAbleRow',
};

export default DragAbleRow;
